package wxapp

import (
	"crypto/sha1"
	"encoding/hex"
	"fmt"
	"io"
	"math/rand"
	"sort"
	"time"
)

var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
func GetNonceStr(n int) string {
	r := rand.New(rand.NewSource(time.Now().UnixNano()))

	b := make([]rune, n)
	for i := range b {
		b[i] = letters[r.Intn(len(letters))]
	}
	return string(b)
}

func SignSHA1(signstr string) string {
	hasher := sha1.New()
	hasher.Write([]byte(signstr))
	sign := hex.EncodeToString(hasher.Sum(nil))
	return sign
}

type WeixinParam struct {
	token string
	signature string
	timestamp string
	nonce string
	echostr string
}

func str2sha1(data string)string{
	t:=sha1.New()
	io.WriteString(t,data)
	return fmt.Sprintf("%x",t.Sum(nil))
}

//消息推送接入请求验证
func WeixinCheck(p WeixinParam) string {
	tmps:=[]string{p.token, p.timestamp, p.nonce}
	sort.Strings(tmps)
	tmpStr:=tmps[0]+tmps[1]+tmps[2]
	tmp:=str2sha1(tmpStr)
	if tmp == p.signature{
		return p.echostr
	} else {
		return ""
	}
}
